package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-03-23
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    /**
     * 保存自媒体用户
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser user) {
        //1.根据APP用户ID 查询 该APP用户是否已经有自媒体用户
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId, user.getApUserId());
        WmUser one = this.getOne(queryWrapper);
        //1.1 如果存在 则直接返回
        if (one != null) {
            return ResponseResult.okResult(one);
        }
        //1.2 不存在则新增  保存完数据库 对象主键值：有
        this.save(user);
        return ResponseResult.okResult(user);
    }

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.校验用户提交参数是否为空
        if (loginDto == null || StringUtils.isBlank(loginDto.getName()) || StringUtils.isBlank(loginDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.根据账户名称查询用户信息（得到用户盐salt信息 跟 正确密文）
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName, loginDto.getName());
        WmUser one = this.getOne(queryWrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //3.校验用户填写密码是否正确
        //3.1 拿着用户填写明文密码+盐 进行Md5加密 得到密文
        String pwdStr = loginDto.getPassword() + one.getSalt();
        String userEnterPwdEncoderStr = DigestUtils.md5DigestAsHex(pwdStr.getBytes());

        //3.2 判断上面步骤得到的密文 跟 数据库中正确密文是否一致
        if (!one.getPassword().equals(userEnterPwdEncoderStr)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4.调用JWT工具类生成令牌
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("userId", one.getId());
        claimMaps.put("userName", one.getName());
        String token = AppJwtUtil.getToken(claimMaps);

        //5.封装响应结果业务数据
        //5.1 数据脱敏
        one.setPassword(null);
        one.setSalt(null);
        one.setPhone(null);

        //5.2 通过Map构建要求响应结果
        HashMap<String, Object> mapResult = new HashMap<>();
        mapResult.put("user", one);
        mapResult.put("token", token);
        return ResponseResult.okResult(mapResult);
    }
}
